//
//  AppDelegate.swift
//  Rainy
//
//  Created by teddy on 4/22/16.
//  Copyright © 2016 teddy. All rights reserved.
//

import UIKit
import CoreData
import Alamofire


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var locationString: String = ""
    
    // 时间间隔: 60s * 60mins = one hour
    let theTimeInterval: NSTimeInterval = 60 * 60
    
    
    // 第一次载入程序完成的时候加载
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        // 隐藏status bar
        application.statusBarHidden = true
        
        /* JPush*/
        // 初始化设置  这里只适配iOS8 以上的版本
        let type: UInt = UIUserNotificationType.Alert.rawValue | UIUserNotificationType.Sound.rawValue | UIUserNotificationType.Badge.rawValue
        JPUSHService.registerForRemoteNotificationTypes(type, categories: nil)
        // MAEK: 生产状态下修改 apsForProduction 配置参数
        JPUSHService.setupWithOption(launchOptions, appKey: "c47bb9f1ef9c74ff8235a5a8", channel: nil, apsForProduction: false)
        /* JPush End*/
        
        // 设置通知option
        let settings = UIUserNotificationSettings(forTypes: UIUserNotificationType.Alert, categories: nil)
        UIApplication.sharedApplication().registerUserNotificationSettings(settings)
        
        // 尽可能多的从后台获取数据
        // UIApplication.sharedApplication().setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)
        
        // 最少时间为1小时
        UIApplication.sharedApplication().setMinimumBackgroundFetchInterval(theTimeInterval)
        
        return true
    }
    
    func application(application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
        print("Complete");
        completionHandler(UIBackgroundFetchResult.NewData)
        if (locationString != "") {
            getData(JPUSHService.registrationID());
        } else {
            print ("No Location!")
        }
    }
    
    func getData(regID: String) -> Void{
        
        var urlPath: String = "http://www.teddylong.net/testNotification.php?location=" + locationString + "&regID=" + regID
        print (urlPath)
        
        urlPath = urlPath.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
        
        let url: NSURL = NSURL(string: urlPath)!
        let request1: NSURLRequest = NSURLRequest(URL: url)
        let response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil
        
        do{
            
            let dataVal = try NSURLConnection.sendSynchronousRequest(request1, returningResponse: response)
            
            print(response)
            do {
                if let jsonResult = try NSJSONSerialization.JSONObjectWithData(dataVal, options: []) as? NSDictionary {
                    print("Synchronous\(jsonResult)")
                }
            } catch let error as NSError {
                print(error.localizedDescription)
            }
            
        }
        catch let error as NSError
        {
            print(error.localizedDescription)
        }
        
        
    }
    
    func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
        /// Required - 注册 DeviceToken
        JPUSHService.registerDeviceToken(deviceToken)
    }

    func applicationWillResignActive(application: UIApplication) {
        
    }
    
    // 接收通知失败
    func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
        print("did Fail To Register For Remote Notifications With Error = \(error)")
    }
    
    // 接收通知成功
    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
        
        JPUSHService.handleRemoteNotification(userInfo)
        completionHandler(UIBackgroundFetchResult.NewData);
    }
    
    // 清除 badge 和 通知栏 的信息
    func applicationWillEnterForeground(application: UIApplication) {
        application.applicationIconBadgeNumber = 0
        application.cancelAllLocalNotifications()
    }

    func applicationDidEnterBackground(application: UIApplication) {
        
    }


    func applicationDidBecomeActive(application: UIApplication) {
        

    }

    func applicationWillTerminate(application: UIApplication) {
        
    }


}

